package com.hyk.controller;

import com.hyk.dto.ApiResult;
import com.hyk.entity.response.IndexResponse;
import com.hyk.service.IUserOrderService;
import com.hyk.service.IUserService;
import com.hyk.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/index")
@Api(tags = "后台首页相关接口")
@CrossOrigin
public class IndexController {

    @Resource
    private IUserOrderService orderService;

    @Resource
    private IUserService userService;

    @PostMapping("/index")
    @ApiOperation("首页数据统计")
    public ApiResult getData() throws ParseException{

        IndexResponse indexResponse = new IndexResponse();
        //销售额
        indexResponse.setTotalSales(orderService.selectSumToBuy(null,null));

        //总用户数
        indexResponse.setTotalUser(userService.count());

        indexResponse.setOrderGoods(orderService.getOrderSum(1));
        indexResponse.setNotOrderGoods(orderService.getOrderSum(0));

        List<String> timeSales = new ArrayList<>();
        List<BigDecimal> weekSales = new ArrayList<>();
        for (int i=6;i>=0;i--){
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String format = simpleDateFormat.format(DateUtils.addDays(new Date(),-i));
            timeSales.add(format);

            //当天的00.00.00开始
            Date parse = simpleDateFormat.parse(format);
            //结束时间
            Date date = DateUtils.addSeconds(
                    DateUtils.addMinutes(
                    DateUtils.addHours(
                            parse,23),59),59);
            BigDecimal bigDecimal = orderService.selectSumToBuy(parse,date);
            weekSales.add(bigDecimal);
        }
        indexResponse.setTimeSales(timeSales);
        indexResponse.setWeekSales(weekSales);
        return R.ok(indexResponse);
    }

}
